package com.tao.gulimall.product.common.exception;


import com.tao.common.exception.BizCodeEnume;
import com.tao.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 数据校验相关的异常处理
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public R handlerValidException(MethodArgumentNotValidException e){
		log.info("数据校验出现问题: {} ",e.getMessage());
		BindingResult bindingResult = e.getBindingResult();
		HashMap<String, String> data = new HashMap<>();
		R error = R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg());
		bindingResult.getFieldErrors().forEach((item)->{
			data.put(item.getField(),item.getDefaultMessage());
		});
		error.put("data", data);
		return error;
	}

	@ExceptionHandler(value = Throwable.class)
	public R handlerException(Throwable e){
		log.info("出现未知错误: {}", e.getMessage());
		return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
	}
}
